import Clain.SafetyEvent;
import Clain.SafetyEventType;
import Clain.SafetyHandler;
import Factory.AgriculturalMachine;
import Command.*;
import Strategy.Coordinate;

import java.util.Scanner;

public class TaskExecutionManager extends SystemManager {
    private MachineManager machineManager;
    private RemoteController remoteController;
    private SafetyHandler safetyHandler;

    public TaskExecutionManager(Scanner scanner, MachineManager machineManager,
                                RemoteController remoteController, SafetyHandler safetyHandler) {
        super(scanner);
        this.machineManager = machineManager;
        this.remoteController = remoteController;
        this.safetyHandler = safetyHandler;
    }

    @Override
    public void manage() {
        while (true) {
            System.out.println("\n=== 任务执行与控制 ===");
            System.out.println("1. 发送启动命令");
            System.out.println("2. 发送停止命令");
            System.out.println("3. 发送执行任务命令");
            System.out.println("4. 处理安全事件");
            System.out.println("5. 返回主菜单");

            int choice = getUserChoice(1, 5, "请输入选择(1-5): ");

            // 当选择 5 时，直接返回
            if (choice == 5) {
                return;
            }

            AgriculturalMachine machine = getSelectedMachine();
            if (machine == null) {
                System.out.println("没有可用的农机设备，请先创建!");
                return;
            }

            switch (choice) {
                case 1:
                    // 启动命令：仅改变状态，不执行任务
                    remoteController.setCommand(new StartOperationCommand(machine));
                    remoteController.executeCommand();
                    System.out.println(machine.getType() + " 已启动");
                    break;
                case 2:
                    remoteController.setCommand(new StopOperationCommand(machine));
                    remoteController.executeCommand();
                    System.out.println(machine.getType() + " 已停止");
                    break;
                case 3:
                    // 执行任务命令：触发一次任务执行和状态输出
                    remoteController.setCommand(new ExecuteTaskCommand(machine));
                    remoteController.executeCommand();

                    // 显示一次状态
                    System.out.println("当前状态: " + machine.getState().getStateName());
                    System.out.println(machine.getStatusDescription());
                    break;
                case 4:
                    handleSafetyEvent();
                    break;
            }
        }
    }

    private AgriculturalMachine getSelectedMachine() {
        // 修改此处，调用 machineManager.getMachines()
        if (machineManager.getMachines().isEmpty()) {
            System.out.println("没有可用的农机设备，请先创建!");
            return null;
        }
        System.out.println("\n选择要操作的农机:");
        for (int i = 0; i < machineManager.getMachines().size(); i++) {
            System.out.printf("%d. %s (状态: %s)\n",
                    i + 1,
                    machineManager.getMachines().get(i).getType(),
                    machineManager.getMachines().get(i).getState());
        }

        int choice = getUserChoice(1, machineManager.getMachines().size(), "请选择农机(1-" + machineManager.getMachines().size() + "): ");
        return machineManager.getMachines().get(choice - 1);
    }

    private  void handleSafetyEvent() {
        // 选择受影响的农机
        AgriculturalMachine machine = getSelectedMachine();
        if (machine == null) {
            System.out.println("没有可用的农机设备，无法处理安全事件!");
            return;
        }

        System.out.println("\n选择安全事件类型:");
        System.out.println("1. 障碍物检测");
        System.out.println("2. 农机故障");
        System.out.println("3. 边界违规");

        int choice = getUserChoice(1, 3, "请输入选择(1-3): ");
        SafetyEventType type = SafetyEventType.values()[choice - 1];

        System.out.print("输入事件描述: ");
        String description = scanner.nextLine();

        // 创建安全事件对象
        SafetyEvent event = new SafetyEvent(type, description);
        event.setSource(machine);
        event.setTimestamp(System.currentTimeMillis());

        // 根据事件类型收集特定信息
        switch (type) {
            case OBSTACLE_DETECTED:
                // 收集障碍物信息
                System.out.print("输入障碍物X坐标: ");
                double obstacleX = Double.parseDouble(scanner.nextLine());
                System.out.print("输入障碍物Y坐标: ");
                double obstacleY = Double.parseDouble(scanner.nextLine());
                System.out.print("输入障碍物类型(岩石/树木/动物等): ");
                String obstacleType = scanner.nextLine();
                System.out.print("输入障碍物尺寸(米): ");
                double obstacleSize = Double.parseDouble(scanner.nextLine());

                event.setLocation(new Coordinate(obstacleX, obstacleY));
                event.setDetails(String.format("%s (尺寸: %.1f米)", obstacleType, obstacleSize));
                break;

            case MACHINE_FAULT:
                // 收集故障信息
                System.out.print("输入故障发生位置X坐标: ");
                double faultX = Double.parseDouble(scanner.nextLine());
                System.out.print("输入故障发生位置Y坐标: ");
                double faultY = Double.parseDouble(scanner.nextLine());
                System.out.print("输入故障代码: ");
                int faultCode = Integer.parseInt(scanner.nextLine());
                System.out.print("输入故障描述: ");
                String faultDesc = scanner.nextLine();

                event.setLocation(new Coordinate(faultX, faultY));
                event.setDetails(String.format("故障代码: %d - %s", faultCode, faultDesc));
                event.setCode(faultCode);
                break;

            case BOUNDARY_VIOLATION:
                // 收集边界违规信息
                System.out.print("输入违规位置X坐标: ");
                double boundaryX = Double.parseDouble(scanner.nextLine());
                System.out.print("输入违规位置Y坐标: ");
                double boundaryY = Double.parseDouble(scanner.nextLine());
                System.out.print("输入违规边界类型(东/南/西/北): ");
                String boundaryType = scanner.nextLine();
                System.out.print("输入违规距离(米): ");
                double boundaryDistance = Double.parseDouble(scanner.nextLine());

                event.setLocation(new Coordinate(boundaryX, boundaryY));
                event.setDetails(String.format("%s边界外 %.1f米", boundaryType, boundaryDistance));
                break;
        }

        // 处理安全事件
        System.out.println("\n🚨 处理安全事件: " + description);
        safetyHandler.handle(event);

        // 显示处理结果
        if (event.isResolved()) {
            System.out.println("✅ 安全事件已成功处理");
        } else {
            System.out.println("⚠️ 安全事件未能完全处理，请检查系统");
        }
    }
}

